package Logic.Guild;

import FrameWork.EventBus.Anno.Receiver;
import FrameWork.EventBus.Anno.Schedule;
import FrameWork.EventBus.EventBusManager;
import FrameWork.EventBus.ScheduleType;
import FrameWork.Model.Player;
import Logic.Guild.Event.ReqJoinGuildEvent;
import Logic.Guild.Event.RespJoinGuildEvent;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class GuildManager {

    private Map<Integer,Guild> guildMap = new ConcurrentHashMap<>();

    public void joinGuild(Player player,int guildId){
//        ReqJoinGuildEvent event = new ReqJoinGuildEvent(player,guildId);
//        event.setMod(ReqJoinGuildEvent.getReqPartInGuild());
        Guild guild = guildMap.get(guildId);
        guild.addGuildMember(player);
//        guild.emit("reqJoinGuild",event);
    }

    public void addGuild(Guild guild){
        guildMap.put(guild.getId(),guild);
    }

    //派送到对应Guild的线程
    @Receiver
    public void acceptJoinGuildReq(final ReqJoinGuildEvent event){
        int id = event.getGuildId();
        Guild guild = guildMap.get(id);
        guild.joinGuild(event);
    }


    @Receiver
    public void acceptJoinGuildResp(RespJoinGuildEvent event){
        Player player = event.getPlayer();
        if (event.getMod()==RespJoinGuildEvent.REQ_CONSUME_GOLD){
           ReqJoinGuildEvent req = new ReqJoinGuildEvent(player,event.getGuildId());
           req.setMod(ReqJoinGuildEvent.getConsumeResource());
            if (player.getGold()>event.getGold()){
               player.alterGold(-event.getGold());
               req.setResult(true);
           }else{
                req.setResult(false);
                System.out.println("金币不足");
            }
            Guild guild = guildMap.get(event.getGuildId());
            guild.emit("reqJoinGuild2",req);
        }
        else if (event.getMod() == RespJoinGuildEvent.FINAL){
            if (event.getResult() == RespJoinGuildEvent.SUCCESS){
                System.out.println(player.getAccount()+"加入公会成功");
            }
            else if (event.getResult() == RespJoinGuildEvent.FULL_LOAD){
                System.out.println("该公会已经满人了");
            }
            else if (event.getResult() == RespJoinGuildEvent.ERROR){
                System.out.println("加入公会失败");
                //回滚金钱
                player.alterGold(event.getGold());
            }
        }
    }

}
